package com.beiing.tianshuai.tianshuai.adapter;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v4.app.NavUtils;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.entity.HuoDongDetailBean;
import com.beiing.tianshuai.tianshuai.util.DateUtil;
import com.beiing.tianshuai.tianshuai.util.EmotionUtils;
import com.beiing.tianshuai.tianshuai.util.SpanStringUtils;
import com.beiing.tianshuai.tianshuai.widget.CircleImageView;
import com.bumptech.glide.Glide;
import com.qmuiteam.qmui.span.QMUITouchableSpan;
import com.qmuiteam.qmui.widget.textview.QMUISpanTouchFixTextView;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by LZQ on 2017/8/7.
 */

public class HuoDongCommentAdapter extends RecyclerView.Adapter implements View.OnClickListener {

    //    private static final String TAG = "HuoDongCommentAdapter";
    private Context mContext;
    private static final int TYPE_COMMENT = 0;
    private static final int TYPE_REPLY = 1;
    private List<HuoDongDetailBean.DataBean.CommentBean> mDatas;
    private LayoutInflater inflater;
    private OnItemViewClickListener mOnItemViewClickListener;
    private OnTextClickListener mOnTextClickListener;
    private OnItemLongClickListener mOnItemLongClickListener;
    private Drawable praise, unPraise;

    public HuoDongCommentAdapter(Context mContext, List<HuoDongDetailBean.DataBean.CommentBean> mDatas) {
        this.mContext = mContext;
        this.mDatas = mDatas;
        inflater = LayoutInflater.from(mContext);
        praise = mContext.getResources().getDrawable(R.drawable.like_red_solid);
        unPraise = mContext.getResources().getDrawable(R.drawable.like_gray_hollow);
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder holder = null;
        switch (viewType) {
            case 0:
                holder = new mViewHolder(inflater.inflate(R.layout.item_huodong_comment, parent, false));
                break;
            case 1:
                holder = new replyViewHolder(inflater.inflate(R.layout.item_active_reply, parent, false));
                break;
        }
        return holder;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
        final HuoDongDetailBean.DataBean.CommentBean commentBean = mDatas.get(position);
        if (viewHolder instanceof mViewHolder) {
            ((mViewHolder) viewHolder).commentName.setText(mDatas.get(position).getName());
            ((mViewHolder) viewHolder).commentUnit.setText(mDatas.get(position).getUnit() + " ·");
            ((mViewHolder) viewHolder).commentPraise.setText(mDatas.get(position).getThing());

            if (mDatas.get(position).getIsThing() == 1) {
                ((mViewHolder) viewHolder).commentPraise.setCompoundDrawablesWithIntrinsicBounds(null, null, praise, null);
            } else {
                ((mViewHolder) viewHolder).commentPraise.setCompoundDrawablesWithIntrinsicBounds(null, null, unPraise, null);
            }
            try {
                String decodeContent = URLDecoder.decode(mDatas.get(position).getContent(), "UTF-8");
                ((mViewHolder) viewHolder).commentContent.setText(SpanStringUtils.getEmotionContent(mContext, ((mViewHolder) viewHolder).commentContent, decodeContent));
            } catch (UnsupportedEncodingException e) {
                ((mViewHolder) viewHolder).commentContent.setText(SpanStringUtils.getEmotionContent(mContext, ((mViewHolder) viewHolder).commentContent, mDatas.get(position).getContent()));
                e.printStackTrace();
            }
            try {
                ((mViewHolder) viewHolder).commentTime.setText(DateUtil.timeStamp2Date(mDatas.get(position).getAddTime(), "MM-dd HH:mm"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            Glide.with(mContext)
                    .load(HttpRequestConstant.USER_PIC_HEAD + mDatas.get(position).getPhoto())
                    .into(((mViewHolder) viewHolder).commentHead);

            ((mViewHolder) viewHolder).commentHead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mOnItemViewClickListener != null){
                        mOnItemViewClickListener.onItemViewClick(view, viewHolder.getAdapterPosition());
                    }
                }
            });
            ((mViewHolder) viewHolder).commentPraise.setTag(position);
            ((mViewHolder) viewHolder).commentPraise.setOnClickListener(this);
        } else if (viewHolder instanceof replyViewHolder) {
            ((replyViewHolder) viewHolder).huodongCommentName.setText(mDatas.get(position).getFName());
            ((replyViewHolder) viewHolder).huodongCommentUnit.setText(mDatas.get(position).getFormUnit() + " ·");
            ((replyViewHolder) viewHolder).huodongCommentPraise.setText(mDatas.get(position).getThing());

            if (mDatas.get(position).getIsThing() == 1) {
                ((replyViewHolder) viewHolder).huodongCommentPraise.setCompoundDrawablesWithIntrinsicBounds(null, null, praise, null);
            } else {
                ((replyViewHolder) viewHolder).huodongCommentPraise.setCompoundDrawablesWithIntrinsicBounds(null, null, unPraise, null);
            }
            String decodeContent;
            try {
                decodeContent = URLDecoder.decode(mDatas.get(position).getContent(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                decodeContent = mDatas.get(position).getContent();
                e.printStackTrace();
            }

            SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
            stringBuilder.append("回复").append("@").append(mDatas.get(position).getTName()).append(": ").append(decodeContent);

            //表情拼接 回复内容
            Resources res = mContext.getResources();
            String regexEmotion = "\\[([\u4e00-\u9fa5\\w+\\.])+\\]";
            Pattern patternEmotion = Pattern.compile(regexEmotion);
            Matcher matcherEmotion = patternEmotion.matcher(stringBuilder);
            while (matcherEmotion.find()) {
                // 获取匹配到的具体字符
                String key = matcherEmotion.group();
                // 匹配字符串的开始位置
                int start = matcherEmotion.start();
                // 利用表情名字获取到对应的图片
                Integer imgRes = EmotionUtils.getImgByName(key);
                // 压缩表情图片
                int size = (int) ((replyViewHolder) viewHolder).huodongReplyContent.getTextSize() * 13 / 10;
                Bitmap bitmap = BitmapFactory.decodeResource(res, imgRes);
                Bitmap scaleBitmap = Bitmap.createScaledBitmap(bitmap, size, size, true);
                ImageSpan span = new ImageSpan(mContext, scaleBitmap);
                stringBuilder.setSpan(span, start, start + key.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

            stringBuilder.setSpan(new QMUITouchableSpan(
                    Color.parseColor("#67A0FF"),
                    Color.parseColor("#67A0FF"),
                    Color.parseColor("#00000000"),
                    Color.parseColor("#E0E0E0")) {
                @Override
                public void onSpanClick(View view) {
                    if (mOnTextClickListener != null) {
                        mOnTextClickListener.onTextClick(view, viewHolder.getAdapterPosition(), 0, commentBean);
                    }
                }
            }, 2, 3 + mDatas.get(position).getTName().length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            ((replyViewHolder) viewHolder).huodongReplyContent.setMovementMethodDefault();
            ((replyViewHolder) viewHolder).huodongReplyContent.setText(stringBuilder);
            String decodeComment;
            try {
                decodeComment = URLDecoder.decode(mDatas.get(position).getComment(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                decodeComment = mDatas.get(position).getComment();
                e.printStackTrace();
            }
            SpannableStringBuilder stringBuilder1 = new SpannableStringBuilder();
            stringBuilder1.append("@").append(mDatas.get(position).getTName()).append(": ").append(decodeComment);

            //表情拼接  原评论内容
            Pattern patternEmotion1 = Pattern.compile(regexEmotion);
            Matcher matcherEmotion1 = patternEmotion1.matcher(stringBuilder1);
            while (matcherEmotion1.find()) {
                // 获取匹配到的具体字符
                String key = matcherEmotion1.group();
                // 匹配字符串的开始位置
                int start = matcherEmotion1.start();
                // 利用表情名字获取到对应的图片
                Integer imgRes = EmotionUtils.getImgByName(key);
                // 压缩表情图片
                int size = (int) ((replyViewHolder) viewHolder).huodongCommentContent.getTextSize() * 13 / 10;
                Bitmap bitmap = BitmapFactory.decodeResource(res, imgRes);
                Bitmap scaleBitmap = Bitmap.createScaledBitmap(bitmap, size, size, true);
                ImageSpan span = new ImageSpan(mContext, scaleBitmap);
                stringBuilder1.setSpan(span, start, start + key.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            stringBuilder1.setSpan(new QMUITouchableSpan(
                    Color.parseColor("#67A0FF"),
                    Color.parseColor("#67A0FF"),
                    Color.parseColor("#00000000"),
                    Color.parseColor("#E0E0E0")) {
                @Override
                public void onSpanClick(View view) {
                    if (mOnTextClickListener != null) {
                        mOnTextClickListener.onTextClick(view, viewHolder.getAdapterPosition(), 1, commentBean);
                    }
                }
            }, 0, 1 + mDatas.get(position).getTName().length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            ((replyViewHolder) viewHolder).huodongCommentContent.setMovementMethodDefault();
            ((replyViewHolder) viewHolder).huodongCommentContent.setText(stringBuilder1);

            ((replyViewHolder) viewHolder).huodongCommentTime.setText(DateUtil.timeStamp2Date(mDatas.get(position).getAddTime(), "MM-dd HH:mm"));
            Glide.with(mContext)
                    .load(HttpRequestConstant.USER_PIC_HEAD + mDatas.get(position).getFPhoto())
                    .into(((replyViewHolder) viewHolder).huodongCommentHead);

            ((replyViewHolder) viewHolder).huodongCommentHead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mOnItemViewClickListener != null){
                        mOnItemViewClickListener.onItemViewClick(view, viewHolder.getAdapterPosition());
                    }
                }
            });
            ((replyViewHolder) viewHolder).huodongCommentPraise.setTag(position);
            ((replyViewHolder) viewHolder).huodongCommentPraise.setOnClickListener(this);

        }
        viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mOnItemViewClickListener != null) {
                    mOnItemViewClickListener.onItemClick(view, viewHolder.getAdapterPosition(), commentBean);
                }
            }
        });

        viewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                if (mOnItemLongClickListener != null) {
                    mOnItemLongClickListener.onItemLongClick(view, viewHolder.getAdapterPosition(), commentBean);
                }
                return false;
            }
        });

    }

    @Override
    public int getItemCount() {
        return mDatas == null ? 0 : mDatas.size();
    }

    @Override
    public int getItemViewType(int position) {
        int result = 0;
        switch (mDatas.get(position).getTableType()) {
            case "0":
                result = TYPE_COMMENT;
                break;
            case "1":
                result = TYPE_REPLY;
                break;
        }
        return result;
    }

    public void deleteItem(int position) {
        mDatas.remove(position);
        notifyItemRemoved(position);
    }

    @Override
    public void onClick(View view) {
        if (mOnItemViewClickListener != null) {
            mOnItemViewClickListener.onItemViewClick(view, (int) view.getTag());
        }
    }

    class mViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.huodong_comment_head)
        CircleImageView commentHead;
        @BindView(R.id.huodong_comment_name)
        TextView commentName;
        @BindView(R.id.huodong_comment_unit)
        TextView commentUnit;
        @BindView(R.id.huodong_comment_praise)
        TextView commentPraise;
        @BindView(R.id.huodong_comment_content)
        TextView commentContent;
        @BindView(R.id.huodong_comment_time)
        TextView commentTime;

        public mViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    class replyViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.huodong_comment_head)
        CircleImageView huodongCommentHead;
        @BindView(R.id.huodong_comment_name)
        TextView huodongCommentName;
        @BindView(R.id.huodong_comment_unit)
        TextView huodongCommentUnit;
        @BindView(R.id.huodong_comment_praise)
        TextView huodongCommentPraise;
        @BindView(R.id.huodong_reply_content)
        QMUISpanTouchFixTextView huodongReplyContent;
        @BindView(R.id.huodong_comment_content)
        QMUISpanTouchFixTextView huodongCommentContent;
        @BindView(R.id.huodong_comment_time)
        TextView huodongCommentTime;

        replyViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public interface OnItemViewClickListener {
        void onItemClick(View view, int position, HuoDongDetailBean.DataBean.CommentBean commentBean);

        void onItemViewClick(View view, int position);
    }

    public void setOnItemViewClickListener(OnItemViewClickListener listener) {
        this.mOnItemViewClickListener = listener;
    }

    public interface OnTextClickListener {
        void onTextClick(View view, int position, int type, HuoDongDetailBean.DataBean.CommentBean commentBean);
    }

    public void setOnTextClickListener(OnTextClickListener listener) {
        this.mOnTextClickListener = listener;
    }

    public interface OnItemLongClickListener {
        void onItemLongClick(View view, int position, HuoDongDetailBean.DataBean.CommentBean commentBean);
    }

    public void setOnItemLongClickListener(OnItemLongClickListener listener) {
        this.mOnItemLongClickListener = listener;
    }
}
